// 数据battle处理
import { battleUserSave, battleUserUpdate } from '@/apis/battle'
import { battleUserStore } from '@/store/battle'
import { battleskillStore } from '@/store/skill'
import { battleDataStore } from '@/store/file'
import {
  NameValue,
  BattleInfoDetail,
  MultiLineData,
  ProcessedText,
  BattleData,
  TargetInfo
} from '@/types/process'
import { id2role, role2id } from '@/utils/role'
/**
    使用Lodash的groupBy函数，可以将这些数据按照造成的追加效果进行分组，然后再统计每个组的数量。
 */
// 作战信息提取
// type ProcessedText = {
//   defeatLines?: string[]
//   deathLines?: string[]
//   allLines?: string[]
//   // allUserLines?: string[];
//   // 打败或被打败的用户
//   currentUsers?: string[]
//   // 所有敌人
//   wholeEnemy?: string[]
//   allBattleInfo?: BattleInfoDetail[]
// }

export function processText(text: string | undefined): ProcessedText {
  if (!text) {
    return { defeatLines: [], deathLines: [] }
  }
  // 换行可能 \n 或者 \r\n
  const lines: string[] = text.split(/\r?\n/)
  let time: string = '00:00:00'
  const defeatLines: string[] = []
  const deathLines: string[] = []
  let concat: boolean = false
  let concat2: boolean = false
  let concat_alline: boolean = false
  const allLines: string[] = []
  const allUserLines: string[] = []
  const currentUsersSet: Set<string> = new Set()
  // const wholeUsers: Set<string> = new Set()
  const wholeUsers: Map<string, string> = new Map()
  // map[name][role_name]

  let userName: string | null = null
  // 效果数据
  const effectData: string[] = []

  lines.forEach((line) => {
    try {
      // ignore contains '(LV' and ignore empty line
      if (!line.trim() || line.includes('(LV')) {
        return
      }
      if (line.startsWith('[')) {
        time = line.substring(1, 9)
        if (!line.includes(')')) {
          concat_alline = true
        }
        allLines.push(line)
        return
      }
      if (concat_alline) {
        const lastIndex = Math.max(allLines.length - 1, 0)
        allLines[lastIndex] = allLines[lastIndex] + line
        concat_alline = false
        return
      }
      if (concat) {
        const lastIndex = Math.max(defeatLines.length - 1, 0)
        defeatLines[lastIndex] = defeatLines[lastIndex] + line
        concat = false
        return
      }
      if (concat2) {
        const lastIndex = Math.max(deathLines.length - 1, 0)
        deathLines[lastIndex] = deathLines[lastIndex] + line
        concat2 = false
        return
      }
      // TODO 需要提取出新的用户名
      if (line.startsWith('击败敌人')) {
        defeatLines.push(time + line)
        if (!line.endsWith(')')) {
          concat = true
        }
      } else if (line.startsWith('角色已死亡')) {
        deathLines.push(time + line)
        if (!line.endsWith(')')) {
          concat2 = true
        }
      }
    } catch (e) {
      console.error('ERR:', (e as Error).message)
    }
  })
  // "20:16:55角色已死亡(豪情灬团子)", extrat '豪情灬团子' to currentUsers
  deathLines.forEach((line) => {
    const user = line.match(/\(.*\)/)
    if (user) {
      const userName = user[0].replace('(', '').replace(')', '')
      currentUsersSet.add(userName)
    }
  })
  // deathLines
  defeatLines.forEach((line) => {
    const user = line.match(/\(.*\)/)
    if (user) {
      const userName = user[0].replace('(', '').replace(')', '')
      currentUsersSet.add(userName)
    }
  })
  // currentUsersSet 添加到wholeUsers
  currentUsersSet.forEach((name) => {
    // 判断是否存在，不存在才添加name
    if (!wholeUsers.has(name)) {
      wholeUsers.set(name, '')
    }
  })

  const currentUsers = Array.from(currentUsersSet)
  const new_user = battleUserStore.getState().check_new_users(currentUsers)
  // if (new_user.length > 0) {
  //   new_user.forEach((user) => {
  //     battleUserSave({ data: { name: user } })
  //   })
  // }
  // userLines
  allLines.forEach((line) => {
    // exclude ', 激励, 持续伤害', 技能值自动恢复, 持续伤害
    if (
      line.includes(', 技能值自动恢复, 持续伤害') ||
      line.includes(', 激励, 持续伤害')
    ) {
      return
    }
    // is_added = false
    let is_added = false
    // 提取所有出现过的用户 wholeUsers
    battleUserStore.getState().storeUsers.forEach((user) => {
      if (line.includes(user.name)) {
        if (!wholeUsers.has(user.name)) {
          wholeUsers.set(user.name, '')
        }
      }
    })

    if (line.includes('追加效果, 战神之力)')) {
      const target_str = line.split(', 追加效果, 战神之力)')[0]
      // split 受到的追加效果 (
      // 提取出名字 '受到的追加效果 ('后面的名字
      userName = target_str.split('受到的追加效果 (')[1]
    }
    if (line.includes('受到')) {
      // 通过技能获取用户
      battleskillStore.getState().storeSkills.forEach((skill) => {
        // , 流星火雨,     , {},
        // 拼接技能   " , skill, "
        //, 暴怒震击,
        const skillStr = ', ' + skill.name + ', '
        if (line.includes(skillStr)) {
          //职业
          skill.role_name
          allUserLines.push(line)
          is_added = true
          // 提取出技能前面的的名字 eg:[19:51:42] 受到生命值 2 (小马哥★★★★★, skill, 持续伤害)
          const target_str = line.split(skillStr)[0]
          // 提取出名字 (后面的名字
          const target = target_str
            .substring(target_str.lastIndexOf('(') + 1, target_str.length)
            .trim()
          // wholeUsers.add(target)
          wholeUsers.set(target, skill.role_name)
        }
      })
    }
    // ignore  '受到的追加效果' or '造成的追加效果'
    if (line.includes('追加效果')) {
      effectData.push(line)
      return
    }
    if (is_added) {
      return
    }
    battleUserStore.getState().storeUsers.forEach((user) => {
      // (法律,  prefix ( endfix ,
      // (user,
      const userStr = '(' + user.name + ','
      if (line.includes(userStr)) {
        allUserLines.push(line)
        is_added = true
      }
    })

    if (is_added) {
      return
    }
    currentUsers.forEach((user) => {
      const userStr = '(' + user + ','
      if (line.includes(userStr)) {
        allUserLines.push(line)
        is_added = true
      }
    })
  })

  //[21:24:23] 受到生命值 35 (龙七, 暴怒震击, 持续伤害)
  //[21:24:27] 受到生命值 177 (龙七, 飞身冲撞)
  const allBattleInfo: BattleInfoDetail[] = allUserLines
    .filter(
      (line) =>
        //不能包含 '生命值 吸收'
        !line.includes('生命值 吸收') &&
        line.includes('生命值') &&
        (line.includes('受到') || line.includes('造成'))
    )
    .map((line) => {
      const time = line.substring(1, 9)
      const action = line.includes('受到') ? '受到' : '造成'
      const skill = line
        .substring(line.lastIndexOf(',') + 1, line.lastIndexOf(')'))
        .trim()
      const target_str = line.split('生命值')[1]
      //[19:06:06] 受到的追加效果 (法律, 能量强化, 增加技能伤害)
      const target = target_str
        .substring(target_str.indexOf('(') + 1, target_str.indexOf(','))
        .trim()
      const count_str = line
        .substring(line.lastIndexOf('生命值') + 3, line.indexOf('('))
        .trim()
      const count = parseInt(count_str, 10)
      return { time, action, skill, target, count }
    })

  // effectData解释
  const allEffectData: BattleInfoDetail[] = effectData.map((line) => {
    const time = line.substring(1, 9)
    const action = line.includes('受到') ? '受到' : '造成'
    // 提取 '反射伤害' or '电力场'
    //[22:39:31] 受到的追加效果 (法律, 神圣洗礼, 不良状态清除)

    const target_str = line.split('追加效果 (')[1]
    // extrat '法律'
    const target = target_str.substring(0, target_str.indexOf(',')).trim()
    // target_str= 法律, 神圣洗礼, 不良状态清除)
    // 提取 '神圣洗礼'
    const skill = target_str.split(', ')[1]
    // extrat '神圣洗礼'

    // count=0
    return { time, action, skill, target, count: 0 }
  })
  // const wholeEnemy = Array.from(wholeUsers)
  // 异步 调用
  processNewUser(wholeUsers, new_user)
  return {
    defeatLines,
    deathLines,
    allBattleInfo,
    wholeUsers,
    userName,
    allUserLines,
    allEffectData
  }
}

// BattleInfo[] 数据，取出最大30的输出伤害，最大的承受伤害
export function processMinMaxTop30Val(battleInfos: BattleInfoDetail[]): {
  out: BattleInfoDetail[]
  received: BattleInfoDetail[]
} {
  // Separate the actions into '受到' (received damage) and '造成' (output damage)
  const outputDamage = battleInfos.filter((info) =>
    info.action.includes('造成')
  )
  const receivedDamage = battleInfos.filter((info) =>
    info.action.includes('受到')
  )

  // Sort each filtered array by the `count` property in descending order
  outputDamage.sort((a, b) => b.count - a.count)
  receivedDamage.sort((a, b) => b.count - a.count)

  // Extract the top 30 values from each sorted array
  const out = outputDamage.slice(0, 20)
  const received = receivedDamage.slice(0, 20)

  // Return an object containing the top 30 values for both received and output damage
  return {
    out,
    received
  }
}
// 按分钟数据处理
export function processSmoothLineData(
  battleInfos: BattleInfoDetail[]
): MultiLineData {
  // Step 1: Filter data into outputDamage and receivedDamage
  const outputDamage = battleInfos.filter((info) =>
    info.action.includes('造成')
  )
  const receivedDamage = battleInfos.filter((info) =>
    info.action.includes('受到')
  )

  // Step 2: Parse and group data by minute for outputDamage
  const dataByMinuteOutput: { [minute: string]: number } = {}
  outputDamage.forEach((info) => {
    const minute = info.time.substring(0, 5) // Extract minute from time string
    if (!dataByMinuteOutput[minute]) {
      dataByMinuteOutput[minute] = 0
    }
    dataByMinuteOutput[minute] += info.count // Aggregate count
  })

  // Step 3: Parse and group data by minute for receivedDamage
  const dataByMinuteReceived: { [minute: string]: number } = {}
  receivedDamage.forEach((info) => {
    const minute = info.time.substring(0, 5) // Extract minute from time
    if (!dataByMinuteReceived[minute]) {
      dataByMinuteReceived[minute] = 0
    }
    dataByMinuteReceived[minute] += info.count // Aggregate count
  })

  // Step 4: Generate a complete set of xAxis data
  const allMinutes = new Set([
    ...Object.keys(dataByMinuteOutput),
    ...Object.keys(dataByMinuteReceived)
  ])
  const xAxisData = Array.from(allMinutes).sort()

  // Step 5: Generate series data aligned with xAxisData
  const seriesDataOutput = xAxisData.map(
    (minute) => dataByMinuteOutput[minute] || 0
  )
  const seriesDataReceived = xAxisData.map(
    (minute) => dataByMinuteReceived[minute] || 0
  )

  // return MultiLineData
  return {
    xAxisData,
    yAxisData: [
      {
        name: '输出伤害',
        data: seriesDataOutput,
        type: 'line',
        smooth: true
      },
      {
        name: '承受伤害',
        data: seriesDataReceived,
        type: 'line',
        smooth: true
      }
    ]
  }
}

// 饼图 ,按用户进行分组
export function processTargetData(
  battleInfos: BattleInfoDetail[]
): NameValue[] {
  const groupedData: { [key: string]: number } = {}

  battleInfos.forEach((info) => {
    if (groupedData[info.target]) {
      groupedData[info.target] += info.count
    } else {
      groupedData[info.target] = info.count
    }
  })

  const pieData = Object.keys(groupedData).map((target) => ({
    value: groupedData[target],
    name: target
  }))

  // 按数值从大到小排序
  pieData.sort((a, b) => b.value - a.value)
  return pieData
}

//技能

export function processSkillData(battleInfos: BattleInfoDetail[]): NameValue[] {
  const groupedData: { [key: string]: number } = {}

  battleInfos.forEach((info) => {
    if (groupedData[info.skill]) {
      groupedData[info.skill] += info.count
    } else {
      groupedData[info.skill] = info.count
    }
  })

  const skillData: NameValue[] = Object.keys(groupedData).map((skill) => ({
    value: groupedData[skill],
    name: skill
  }))

  // 按数值从大到小排序
  skillData.sort((a, b) => b.value - a.value)
  return skillData
}

// 人头时间数据【返回2个数组，时间和人头数】
/**
 * "21:36:38击败敌人 (じ★ve可心)",
 * "21:43:07击败敌人 (巅峰轰二零)",
 * "21:33:28角色已死亡(美术教授)",
 * 提取出括号中的名字+时间顺序排序
 *
 */

export function processSmoothLineDataByDamage(
  battleInfos: string[],
  title1?: string,
  title2?: string
): MultiLineData {
  // Step 1: Filter data into outputDamage and receivedDamage
  const outputDamage = battleInfos.filter((info) => info.includes('击败敌人'))
  const receivedDamage = battleInfos.filter((info) =>
    info.includes('角色已死亡')
  )

  // Step 2: Parse and group data by minute for outputDamage
  const dataByMinuteOutput: { [minute: string]: number } = {}
  outputDamage.forEach((info) => {
    const minute = info.substring(0, 5) // Extract minute from time
    if (!dataByMinuteOutput[minute]) {
      dataByMinuteOutput[minute] = 0
    }
    dataByMinuteOutput[minute] += 1 // Increment count by 1
  })

  // Step 3: Parse and group data by minute for receivedDamage
  const dataByMinuteReceived: { [minute: string]: number } = {}
  receivedDamage.forEach((info) => {
    const minute = info.substring(0, 5) // Extract minute from time
    if (!dataByMinuteReceived[minute]) {
      dataByMinuteReceived[minute] = 0
    }
    dataByMinuteReceived[minute] += 1 // Increment count by 1
  })

  // Step 4: Generate xAxis data and series data
  const xAxisData = Array.from(
    new Set([
      ...Object.keys(dataByMinuteOutput),
      ...Object.keys(dataByMinuteReceived)
    ])
  ).sort()
  const seriesDataOutput = xAxisData.map(
    (minute) => dataByMinuteOutput[minute] || 0
  )
  const seriesDataReceived = xAxisData.map(
    (minute) => dataByMinuteReceived[minute] || 0
  )
  return {
    xAxisData,
    yAxisData: [
      {
        name: title1 ? title1 : '输出伤害',
        data: seriesDataOutput,
        type: 'line',
        smooth: true
      },
      {
        name: title2 ? title2 : '承受伤害',
        data: seriesDataReceived,
        type: 'line',
        smooth: true
      }
    ]
  }
}

// lint ignore: ignore unused variables
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function processSummaryData(
  battleInfos: BattleInfoDetail[],
  wholeUsers: Map<string, string>
) {
  // Step 1: Initialize a map to track each target's output and received damage
  const targetMap: { [key: string]: TargetInfo } = {}

  // Step 2: Iterate through battleInfos to update the map
  battleInfos.forEach((info) => {
    if (!targetMap[info.target]) {
      const role_name = info.action.includes('受到')
        ? fetch_by_skill(info.skill)
        : ''
      targetMap[info.target] = {
        name: info.target,
        //wholeUsers.get(info.target) ??
        role: role_name,
        receive: 0,
        output: 0
      }
    }
    if (!targetMap[info.target].role && info.action.includes('受到')) {
      const role = fetch_by_skill(info.skill)
      if (role) {
        targetMap[info.target].role = role
      }
    }

    if (info.action.includes('造成')) {
      targetMap[info.target].output += info.count
    }
    if (info.action.includes('受到')) {
      targetMap[info.target].receive += info.count
    }
  })

  console.log('whole enemy:', wholeUsers)
  // Step 3: Ensure all enemies in wholeEnemy are in the targetMap
  // wholeEnemy.forEach((enemy) => {
  //   if (!targetMap[enemy]) {
  //     targetMap[enemy] = { name: enemy, receive: BigInt(0), output: BigInt(0) };
  //   }
  // });

  // Step 4: Calculate total output and received damage
  const totalOutputDamage = Object.values(targetMap).reduce(
    (acc, target) => acc + target.output,
    0
  )
  const totalReceivedDamage = Object.values(targetMap).reduce(
    (acc, target) => acc + target.receive,
    0
  )

  // Step 5: Convert the map to an array of TargetInfo objects
  const targets = Object.values(targetMap)
  targets.sort((a, b) => {
    if (b.receive === a.receive) {
      return Number(b.output - a.output)
    }
    return Number(b.receive - a.receive)
  })
  // update wholeUsers2db
  checkRoleAndUpdateByTarget(targets, wholeUsers)
  return {
    totalOutputDamage,
    totalReceivedDamage,
    targets
  }
}

// 通过skill 获取role_name
function fetch_by_skill(name: string) {
  const skill = battleskillStore
    .getState()
    .storeSkills.find((s) => s.name === name)
  return skill ? skill.role_name : ''
}

// processText and store2Store
export function processTextAndStore(content: string | undefined, id: string) {
  const ptxt = processText(content)
  const outData =
    ptxt.allBattleInfo?.filter((info) => info.action.includes('造成')) || []
  const inData =
    ptxt.allBattleInfo?.filter((info) => info.action.includes('受到')) || []
  const skillAgg = processEffectDataCountGroupBySkill(
    ptxt.allEffectData || [],
    '受到'
  )
  const buffAgg = processEffectDataCountGroupBySkill(
    ptxt.allEffectData || [],
    '受到',
    '神圣洗礼',
    '净化术',
    '治愈之风'
  )
  console.log('skillAgg:', skillAgg)
  const damageData = processSmoothLineData(ptxt.allBattleInfo || [])
  const outPieOption = processTargetData(outData)
  const inPieOption = processTargetData(inData)
  const outSkillOption: NameValue[] = processSkillData(outData)
  const inSkillOption = processSkillData(inData)
  const headCount = processSmoothLineDataByDamage(
    ptxt.defeatLines || [],
    '斩杀人头',
    '死亡次数'
  )
  const summaryData = processSummaryData(
    ptxt.allBattleInfo || [],
    ptxt.wholeUsers || new Map()
  )
  const top30Count = processMinMaxTop30Val(ptxt.allBattleInfo || [])
  // const targets = summaryData.targets // 获取targets数据
  const kill = processLillAndDeaths(ptxt.defeatLines || [])
  const death = processLillAndDeaths(ptxt.deathLines || [])
  const roleStat = processRoleByTarget(summaryData.targets)

  const data: BattleData = {
    smoothlineOption: damageData,
    skillAgg,
    roleStat,
    buffAgg,
    inPieOption,
    outPieOption,
    inSkillOption,
    outSkillOption,
    headCount,
    top30Count,
    summary: {
      encounter: summaryData.targets.length,
      output: summaryData.totalOutputDamage,
      receive: summaryData.totalReceivedDamage,
      death: ptxt.deathLines ? ptxt.deathLines.length : 0,
      kill: ptxt.defeatLines ? ptxt.defeatLines.length : 0
    },
    targets: summaryData.targets,
    kill: kill,
    death: death,
    userName: ptxt.userName
  }
  battleDataStore.getState().addText(id || '', data)
}

/**
 *
 * @param lines 提取 ()中的名字 并计数
 *
 * 击败敌人 (仲裁者)
 * 击败敌人 (仲裁者)
 *  仲裁者 2
 *
 * @returns
 */
export function processLillAndDeaths(lines: string[]): NameValue[] {
  const groupedData: { [key: string]: number } = {}
  lines.forEach((line) => {
    const user = line.match(/\(.*\)/)
    if (user) {
      const userName = user[0].replace('(', '').replace(')', '')
      if (groupedData[userName]) {
        groupedData[userName] += 1
      } else {
        groupedData[userName] = 1
      }
    }
  })
  const pieData = Object.keys(groupedData).map((target) => ({
    value: groupedData[target],
    name: target
  }))

  // 按数值从大到小排序
  pieData.sort((a, b) => b.value - a.value)
  return pieData
}

// 承受技能次数，输出技能次数 饼图
export function processEffectDataCount(
  battleInfos: BattleInfoDetail[]
): NameValue[] {
  const groupedData: { [key: string]: number } = {}

  battleInfos.forEach((info) => {
    if (groupedData[info.skill]) {
      groupedData[info.skill] += info.count
    } else {
      groupedData[info.skill] = info.count
    }
  })

  const effectData: NameValue[] = Object.keys(groupedData).map((skill) => ({
    value: groupedData[skill],
    name: skill
  }))

  // 按数值从大到小排序
  effectData.sort((a, b) => b.value - a.value)
  return effectData
}

// MultiLineData，按分钟数据处理, 按技能分组
export function processEffectDataCountGroupBySkill(
  battleInfos: BattleInfoDetail[],
  filter1: string,
  ...filters: string[]
): MultiLineData {
  // Step 1: all skill xSeries
  const skillSet = new Set<string>()

  // must filter1
  const filteredBattleInfos = battleInfos
    .filter((info) => info.action.includes(filter1))
    .filter((info) => {
      if (filters.length > 0) {
        return filters.includes(info.skill)
      }
      return true
    })

  filteredBattleInfos.forEach((info) => {
    skillSet.add(info.skill)
  })

  // Step 2: Parse and group data by minute for skills
  const dataByMinute: { [minute: string]: { [skill: string]: number } } = {}
  filteredBattleInfos.forEach((info) => {
    const minute = info.time.substring(0, 5) // Extract minute from time
    if (!dataByMinute[minute]) {
      dataByMinute[minute] = {}
    }
    if (!dataByMinute[minute][info.skill]) {
      dataByMinute[minute][info.skill] = 0
    }
    dataByMinute[minute][info.skill] += 1
  })

  // Ensure yAxisData is correctly constructed
  const yAxisData = Array.from(skillSet).map((skill) => ({
    name: skill,
    data: Object.keys(dataByMinute).map(
      (minute) => dataByMinute[minute][skill] || 0
    ),
    type: 'line',
    smooth: true
  }))

  return {
    xAxisData: Object.keys(dataByMinute),
    yAxisData: yAxisData
  }
}

/**
 *
 * @param skillAgg TargetInfo[]
 * @returns NameValue[]  name value(number)
 */
export function processRoleByTarget(targetInfos: TargetInfo[]): NameValue[] {
  const roleMap: {
    [role: string]: { totalOutput: number; totalReceive: number; count: number }
  } = {}

  targetInfos.forEach((target) => {
    if (!roleMap[target.role]) {
      roleMap[target.role] = { totalOutput: 0, totalReceive: 0, count: 0 }
    }
    roleMap[target.role].totalReceive += target.receive
    roleMap[target.role].count += 1
  })

  const nameValueArray = Object.keys(roleMap).map((role) => ({
    name: `${role} (${roleMap[role].count})`,
    length: roleMap[role].count,
    value: roleMap[role].totalReceive
  }))

  return nameValueArray
}

// 新加的人员数据，如果没有职业，则通过技能获取职业
export function processNewUser(
  wholeUsers: Map<string, string>,
  newUsers: string[]
) {
  newUsers.forEach((name) => {
    //忽略 '红队' '蓝队' 开头的名字
    if (name.startsWith('红队') || name.startsWith('蓝队')) {
      return
    }
    if (wholeUsers.has(name)) {
      const role_name = wholeUsers.get(name)
      const role_id = role2id(role_name || '')
      battleUserSave({ data: { name: name, role: role_id } })
    } else {
      battleUserSave({ data: { name: name } })
    }
  })
}

// 检查职业，如果对不上，则更新
export function checkRoleAndUpdateByTarget(
  targetInfos: TargetInfo[],
  wholeUsers: Map<string, string>
) {
  /**
   * 比较storeUsers和targetInfos，如果role对不上，则更新
   */
  // wholeUsers.get(info.target)
  // 把空的role使用 wholeUsers.get(info.target)填充
  const users = battleUserStore.getState().storeUsers
  targetInfos.forEach((target) => {
    const role = wholeUsers.get(target.name)
    if (!target.role && role && role !== target.role) {
      // 更新role
      target.role = role
    }
    // 没匹配到，从storeUsers中找
    // if (!target.role) {
    //   for (const user of users) {
    //     if (target.name === user.name) {
    //       const roleName = id2role(user.role)
    //       if (roleName) {
    //         target.role = roleName
    //         break
    //       }
    //     }
    //   }
    // }
    /**
     * 1:法师 2:战士 3:暗影 4:机器 5:龙   6:刀锋 7:弓
     * TODO 这段逻辑需要修复
     */
    const user = users.find((u) => u.name === target.name)
    if (!user) {
      return
    }
    // id2Role
    const roleId = role2id(target.role)
    if (user && user.role !== roleId && roleId != 0) {
      // 同时更新storeUsers
      // 如果是0 忽略
      if (roleId != 0) {
        user.role = roleId
        battleUserUpdate({
          data: { id: user.id, name: target.name, role: roleId }
        })
        battleUserStore.getState().update_user(user)
      } else {
        console.log(`Role ID is 0, ignoring update for user: ${user.name}`)
      }
    }
    if (roleId == 0 && user && user.role) {
      target.role = id2role(user.role)
    }
  })
}
